package controllers

import (
	"github.com/astaxie/beego"
	"time"
	"strconv"
	"strings"
	"math/rand"
	"fmt"
)

type JsonReturnData_Message struct {
	Code int
	Data string
}

func Json_Message(c *beego.Controller, code int, data string) {
	json_error := JsonReturnData_Message{Code:code, Data:data }
	c.Data["json"] = &json_error
	c.ServeJSON()
	c.StopRun()
}

func Message(c *beego.Controller, redirectURL string, message string, ExtraInfo string, back bool) {
	c.Data["Message"] = message
	c.Data["TargetURL"] = redirectURL
	if back {
		c.Data["script"] = `<script type="text/javascript">
		function back(secs) {
		var jumpTo = document.getElementById('jumpTo');
		jumpTo.innerHTML = secs;
		if (--secs > 0) {
		setTimeout("back(" + secs + ")", 1000);
		}
else {
history.go(-1);
}
}
back(3);
</script>`
	} else {
		c.Data["script"] = fmt.Sprintf(`<script type="text/javascript">
		countDown(3, "%s");
	</script>`, redirectURL)
	}
	c.TplName = "message.html"
	c.Render()
	c.StopRun()
}

func Message_noauto(c *beego.Controller, redirectURL string, message string, ExtraInfo string, back bool) {
	message = strings.Replace(message, "\r\n", "<br>", -1)
	c.Data["Message"] = message
	c.Data["TargetURL"] = redirectURL
	c.Data["script"] = ""
	c.TplName = "message.html"
	c.Render()
	c.StopRun()
}

func RandString(length int) string {
	rand.Seed(time.Now().UnixNano())
	rs := make([]string, length)
	for start := 0; start < length; start++ {
		t := rand.Intn(3)
		if t == 0 {
			rs = append(rs, strconv.Itoa(rand.Intn(10)))
		} else if t == 1 {
			rs = append(rs, string(rand.Intn(26) + 65))
		} else {
			rs = append(rs, string(rand.Intn(26) + 97))
		}
	}
	return strings.Join(rs, "")
}

func  SetPaginator(c *beego.Controller,per int, nums int64) *Paginator {
	p := NewPaginator(c.Ctx.Request, per, nums)
	c.Data["paginator"] = p
	return p
}